package cn.itsource.ymcc.mq;

import cn.itsource.ymcc.domain.MediaFile;
import cn.itsource.ymcc.exception.GlobalException;
import cn.itsource.ymcc.service.IMediaFileService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

@Component
@Slf4j
@RocketMQMessageListener(consumerGroup = "consumer-group",
        topic = "topic-media",
        selectorExpression = "*",messageModel = MessageModel.CLUSTERING
)
public class MessageConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IMediaFileService mediaFileService;

    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            String jsonStr = new String(messageExt.getBody(),"utf-8");
            MediaFile mediaFile = JSON.parseObject(jsonStr,MediaFile.class);

            log.info("mediaFile:",mediaFile);
            if(mediaFile!=null){
                mediaFileService.handleFile2m3u8(mediaFile);
            }else{
                log.info("jsonStr:",jsonStr);
                throw new GlobalException("投递消息，消费者异常！");

            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }
}
